<template>
  <div v-if="subCate.saleProperties"
       class="filter">
    <cate-filter-item v-model="brandIndex"
                      :data="subCate.brands"
                      label="品牌"
                      @change="handleChange"/>
    <cate-filter-item v-for="(filter, index) in subCate.saleProperties"
                      v-model="attrIndex[index]"
                      :data="filter.properties"
                      :label="filter.name"
                      @change="handleChange"/>
  </div>
</template>

<script lang="ts"
        setup>
import CateFilterItem from '@/components/library/CateFilterItem.vue'
import type {SubCategory} from '@/types/category'
import {computed, ref, toRefs, watch} from 'vue'
import {useRoute} from 'vue-router'

let props = defineProps<{
  data: SubCategory,
  search: Function
}>()
let {data: subCate} = toRefs(props)

let route = useRoute()

watch(() => subCate.value, () => {
  if (!subCate.value.id) return
  handleChange()
}, {
  immediate: true
})


let brandIndex = ref<number>(0)
let brandId = computed(() => {
  return subCate.value.brands?.[brandIndex.value].id
})


let attrIndex = ref<number[]>([])
watch(() => subCate.value.saleProperties, () => {
  let list: number[] = []
  list.length = subCate.value.saleProperties?.length ?? 0
  attrIndex.value = list?.fill(0)
})
let attrs = computed(() => {
  return attrIndex.value.map((value, index) => {
    if (value === 0) return null
    let group = subCate.value.saleProperties?.[index]
    let res = group?.properties?.[value]
    if (!res) return null
    return {groupName: group?.name, propertyName: res.name}
  }).filter(i => i)
})

// 搜索的过滤参数
let searchData = computed(() => ({
  attrs: attrs.value,
  ...brandId.value !== '-1' ? {brandId: brandId.value} : {},
  categoryId: route.params.id
}))

function handleChange() {
  props.search(searchData.value)
}
</script>

<style lang="less"
       scoped>
.filter {
  padding: 25px;
  background-color: #fff;
}
</style>